import { FC, useRef, useState } from 'react'
import { ModalForm, ProFormInstance } from '@ant-design/pro-form'
import { Button, message, Transfer } from 'antd'
import { useMount } from 'ahooks'
import { listByUserId, updateUserRole } from '@/api/auth/role'
import { SetRoleVO } from '@/model/auth/SetRoleVO'
import { SetRoleDTO } from '@/model/auth/SetRoleDTO'

interface SetRoleParam {
  userId: number
}

const UsersSetRoleForm: FC<SetRoleParam> = (props) => {
  const { userId } = props
  const formRef = useRef<ProFormInstance>()
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  }
  const [selectedKeys, setSelectedKeys] = useState([])
  const [targetKeys, setTargetKeys] = useState([])
  const [roles, setRoles] = useState<Array<SetRoleVO>>([])

  useMount(async () => {
    const rolesResp = await listByUserId(userId)
    setRoles(rolesResp.map((item) => {
      return {
        ...item,
        key: item.id,
      }
    }))

    const targetKeyTemp = rolesResp.filter((item) => item.check).map((item) => item.id)
    setTargetKeys(targetKeyTemp)
  })

  const onSelectChange = (sourceSelectedKeys, targetSelectedKeys) => {
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys])
  }

  const onChange = (nextTargetKeys) => {
    setTargetKeys(nextTargetKeys)
  }

  return (
    <div className="user-set-role-form">
      <ModalForm<SetRoleDTO>
        formRef={formRef}
        title="设置角色"
        layout="horizontal"
        trigger={
          <Button type="link">
            设置角色
          </Button>
        }
        {...formItemLayout}
        onFinish={async () => {
          const setRoleDTO = new SetRoleDTO()
          setRoleDTO.userId = userId
          setRoleDTO.roleIds = targetKeys
          await updateUserRole(setRoleDTO)
          message.success('设置成功')
          return true
        }}
      >
        <Transfer
          dataSource={roles}
          titles={['未有角色', '已有角色']}
          targetKeys={targetKeys}
          selectedKeys={selectedKeys}
          onChange={onChange}
          onSelectChange={onSelectChange}
          render={(item) => item.name}
        />
      </ModalForm>
    </div>
  )
}

export default UsersSetRoleForm
